package mm.chenchen.exception;


import lombok.extern.slf4j.Slf4j;
import mm.chenchen.utils.R;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 用用异常处理类
 */

@RestControllerAdvice
@Slf4j
public class ExceptionController {
    @ExceptionHandler(NullPointerException.class)
    public R handlerNullPointException(HttpServletRequest request, NullPointerException ex) {
        log.error("空指针异常捕获");
        if (ex != null) {
            log.error(ex.getMessage(), ex);
            return R.error("数据异常,请查看后台日志处理!");
        }
        log.error("未知错误!");
        return R.error("未知错误!");
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("运行异常捕获");
        StringBuilder sb = new StringBuilder();

        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            sb.append("[").append(fieldName).append("]").append(error.getDefaultMessage()).append(";    ");
        });

        if (ex != null) {
            log.error(ex.getMessage(), ex);
            return R.error("参数校验错误,校验信息为: "+sb);
        }
        log.error("未知错误!");
        return R.error("未知错误!");
    }


    @ExceptionHandler(RuntimeException.class)
    public R handlerRuntimeException(RuntimeException ex) {
        log.error("运行异常捕获");
        if (ex != null) {
            log.error(ex.getMessage(), ex);
            return R.error("运行错误,请查看后台日志处理!");
        }
        log.error("未知错误!");
        return R.error("未知错误!");
    }

    @ExceptionHandler(RRException.class)
    public R handlerRRException(RRException ex) {
        log.error("自定义异常捕获");
        if (ex != null) {
            log.error(ex.getMessage(), ex);
            return R.error(ex.getMessage());
        }
        log.error("未知错误!");
        return R.error();
    }

    @ExceptionHandler(Exception.class)
    public R handlerMaxUploadSizeExceededException(Exception ex) {
        log.error("通用异常捕获");
        if (ex != null) {
            log.error(ex.getMessage(), ex);
            return R.error("运行错误,请查看后台日志处理!");
        }
        log.error("未知错误!");
        return R.error("未知错误!");
    }
}
